using System;
using System.Collections.Generic;
using System.Linq;
using ReagentStore.ERM;
using ReagentStore.Resources.Properties;

namespace ReagentStore.DAL
{
	public class CatalogDAL : IDALBase<Catalog>
	{
		#region Implementation of IDALBase<T>

		public IList<Catalog> GetEntities()
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Catalogs.ToList();
		}

		public Catalog GetEntityById(int id)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Catalogs.SingleOrDefault(s => id.Equals(s.CatalogID));
		}

		public void Insert(Catalog catalog)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				db.Catalogs.AddObject(catalog);
				db.SaveChanges();
			}
		}

		public void Update(Catalog catalog)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Catalog exist = GetEntityById(catalog.CatalogID);
				db.Catalogs.Attach(exist);

				exist.Name = catalog.Name;

				db.SaveChanges();
			}
		}

		public void Delete(Catalog catalog)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Catalog defaultCatalog =
					db.Catalogs.SingleOrDefault(
						s => DefaultResources.DEFAULT_CATALOG_NAME.Equals(s.Name, StringComparison.CurrentCultureIgnoreCase));
				Catalog exist = GetEntityById(catalog.CatalogID);

				if ((exist == null)
				    || (defaultCatalog == null))
					return;

				if (exist.CatalogID == defaultCatalog.CatalogID)
					return;

				db.Catalogs.Attach(exist);
				List<Reagent> reagents = exist.Reagents.ToList();
				reagents.ForEach(reagent => reagent.CatalogID = defaultCatalog.CatalogID);

				db.Catalogs.DeleteObject(exist);
				db.SaveChanges();
			}
		}

		#endregion
	}
}